package engine

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"runtime/debug"
	"sync/atomic"
	"syscall"
	"time"

	hbtp "github.com/mgr9525/HyperByte-Transfer-Protocol"
	"github.com/sirupsen/logrus"
	"github.com/yggworldtree/go-core/utils"
	"github.com/yggworldtree/go-server/comm"
)

type Manager struct {
	ctx    context.Context
	cncl   context.CancelFunc
	procln uint32

	hbtpEgn *hbtp.Engine
}

var (
	mgr *Manager
)

func init() {
	mgr = &Manager{}
	mgr.ctx, mgr.cncl = context.WithCancel(context.Background())
}
func Mgr() *Manager {
	return mgr
}
func Wait() {
	for !utils.EndContext(mgr.ctx) {
		if mgr == nil || mgr.cncl == nil {
			break
		}
		time.Sleep(time.Millisecond * 10)
	}
	tms := time.Now()
	for time.Since(tms).Seconds() < 20 {
		if mgr.procln <= 0 {
			break
		}
	}
}
func Stop() {
	if mgr != nil && mgr.cncl != nil {
		mgr.cncl()
		mgr.cncl = nil
	}
	if mgr.hbtpEgn != nil {
		mgr.hbtpEgn.Close()
	}
}

func Start() error {
	csig := make(chan os.Signal, 1)
	signal.Notify(csig, os.Interrupt, syscall.SIGALRM)
	go func() {
		s := <-csig
		logrus.Infof("get signal(%d):%s", s, s.String())
		Stop()
	}()
	go mgr.init()

	return nil
}
func (c *Manager) init() {
	defer func() {
		if err := recover(); err != nil {
			logrus.Errorf("Manager init:%+v", err)
			logrus.Errorf("%s", string(debug.Stack()))
		}
	}()

	go func() {
		c.AddPorc(1)
		defer c.AddPorc(-1)
		c.hbtpEgn = hbtp.NewEngine(mgr.ctx)
		// enhbtpEgng.RegFun(1, hbtp.RPCFunHandle(&routehb.ClientRPC{}))
		// hbtpEgn.RegFun(2, hbtp.RPCFunHandle(&routehb.RunnerRPC{}))
		//eng.RegFun(3, hbtp.RPCFunHandle(&routehb.SysRPC{}))
		if err := c.hbtpEgn.Run(fmt.Sprintf(":%d", comm.HbtpPort)); err != nil {
			logrus.Error("StartConnEngine run err:" + err.Error())
			Stop()
		}
	}()
}
func (c *Manager) AddPorc(a int) {
	if a == 0 || (a < 0 && c.procln <= 0) {
		return
	}
	atomic.AddUint32(&c.procln, uint32(a))
}
